<template>
  <van-button
    class="follow-btn"
    round
    size="small"
    @click="onFollow"
    v-if="is_followed === true"
    >已关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    :loading="isFollowLoading"
    size="small"
    icon="plus"
    @click="onFollow"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  model: {
    prop: 'is_followed',
    event: 'updatefollow'
  }, // 接收父组件传来的值
  props: {
    is_followed: {
      type: Boolean,
      require: true
    },
    aut_id: {
      type: Number,
      require: true
    }
  },
  // 定义属性
  data() {
    return {
      isFollowLoading: false
    }
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    async onFollow() {
      // 开启按钮的 loading 状态
      this.isFollowLoading = true
      try {
        // 如果已关注，则取消关注
        const authorId = this.aut_id
        if (this.is_followed) {
          const res = await deleteFollow(authorId)
          console.log(res)
        } else {
          // 否则添加关注
          const res = await addFollow(authorId)
          console.log(res)
        }
        this.$toast.success('操作成功')
        // 更新视图
        this.$emit('updatefollow', !this.is_followed)
      } catch (err) {
        console.log(err)
        this.$toast.fail('操作失败')
      }

      // 关闭按钮的 loading 状态
      this.isFollowLoading = false
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {}
}
</script>

<style lang="less"></style>
